package com.apes.hr.transfer.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.generator.service.SequenceService;
import com.apes.framework.jpa.logger.ApesLoggerService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.websocket.WsPublisher;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.EventUtil;
import com.apes.framework.util.MapUtil;
import com.apes.hr.base.model.*;
import com.apes.hr.base.repository.EmployeeRepository;
import com.apes.hr.base.repository.JobRepository;
import com.apes.hr.base.repository.StaffingRepository;
import com.apes.hr.base.repository.TransferRecordRepository;
import com.apes.hr.recruit.model.ApplyJobOrder;
import com.apes.hr.recruit.model.EmployContract;
import com.apes.hr.recruit.model.RecruitOrder;
import com.apes.hr.recruit.repository.ApplyJobOrderRepository;
import com.apes.hr.recruit.repository.EmployContractRepository;
import com.apes.hr.recruit.repository.RecruitOrderRepository;
import com.apes.hr.recruit.service.ApplyJobOrderService;
import com.apes.hr.thirdParty.dingidng.model.DingDingToken;
import com.apes.hr.thirdParty.dingidng.service.DingDingService;
import com.apes.hr.transfer.model.QuitJobOrder;
import com.apes.hr.transfer.repository.QuitJobOrderRepository;
import com.apes.hr.transfer.repository.TransferApplicationItemRepository;
import com.apes.hr.transfer.repository.WorkHandoverRepository;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.frame.model.Branch;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.rbac.model.LocalPermitItem;
import com.apes.scm.rbac.model.Post;
import com.apes.scm.rbac.model.User;
import com.apes.scm.rbac.repository.LocalPermitItemRepository;
import com.apes.scm.rbac.repository.PostRepository;
import com.apes.scm.rbac.repository.UserRepository;
import com.apes.scm.rbac.service.UserService;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 功能：离职申请单
 *
 * @author HuJianlin
 * @create 2018-03-19 14:35
 */
@Service("hrQuitJobOrderService")
public class QuitJobOrderService extends DomainService {

    @Autowired
    public QuitJobOrderRepository quitJobOrderRepository;

    @Autowired
    EmployeeRepository employeeRepository;

    @Autowired
    StaffingRepository staffingRepository;

    @Autowired
    EnumerationRepository enumerationRepository;

    @Autowired
    WorkHandoverRepository workHandoverRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    UserService userService;

    @Autowired
    PostRepository postRepository;

    @Autowired
    ApplyJobOrderRepository applyJobOrderRepository;
    @Autowired
    ApplyJobOrderService applyJobOrderService;

    @Autowired
    TransferApplicationItemRepository transferApplicationItemRepository;

    @Autowired
    RecruitOrderRepository recruitOrderRepository;

    @Autowired
    JobRepository jobRepository;

    @Autowired
    TransferRecordRepository transferRecordRepository;

    @Autowired
    DingDingService dingService;

    @Autowired
    DingDingToken dingDingToken;
    @Autowired
    EmployContractRepository employContractRepository;
    @Autowired
    ApesLoggerService apesLoggerService;
    @Autowired
    WsPublisher wsPublisher;
    @Autowired
    SequenceService sequenceService;
    @Autowired
    MongoTemplate mongoTemplate;

    /***
     * 功能：创建
     * @param request
     * @return
     */
    public QuitJobOrder create(SimpleRequest request) {

        QuitJobOrder quitJobOrder = request.getO(QuitJobOrder.class);
        Employee employee = quitJobOrder.getEmployee();
        quitJobOrder.setPost(employee.getPost());
        quitJobOrder.setJob(employee.getJob());
        quitJobOrder.setRank(employee.getRank());
        if(exist(employee)) {
            throw new RuntimeException("当前员工已有未完成的离职单，不允许重复创建！");
        }
        Enumeration enumeration = enumerationRepository.findOne("000416");
        quitJobOrder.setQuitClass(enumeration);
        quitJobOrder.setState("create");
        checkEntryDate(request,enumeration);
        //将人员档案的信息保存到离职申请单中（方便统计查询）

        //保存后自动转OA
        quitJobOrder = quitJobOrderRepository.saveAndFlush(quitJobOrder);
        invoke("hr.transfer.quitJobOrder.oa", quitJobOrder);

        return quitJobOrder;
    }


    /**
     *  将离职申请单的数据写入
     * @param quitJobOrder
     * @param employee
     * @return
     */
    private QuitJobOrder setQuitJobOrder(QuitJobOrder quitJobOrder,Employee employee){
        quitJobOrder.setEmployee(employee);
        quitJobOrder.setOrigin(employee.getOrigin());
        quitJobOrder.setWorkBranch(employee.getWorkBranch());
        quitJobOrder.setPost(employee.getPost());
        quitJobOrder.setJob(employee.getJob());
        quitJobOrder.setPostDescribe(employee.getPostDescribe());
        quitJobOrder.setOnDutyState(employee.getOnDutyState());
        quitJobOrder.setRank(employee.getRank());
        quitJobOrder.setEntryDate(employee.getEntryDate());
        quitJobOrder.setApplyDay(new Date());
        quitJobOrder.setRealLastDay(quitJobOrder.getPlanLastDay());
        quitJobOrder.setQuitJobDeptOpinionDate(quitJobOrder.getPlanLastDay());
        quitJobOrder.setApproveLastDay(quitJobOrder.getPlanLastDay());
        quitJobOrder.setHrOpinionDay(quitJobOrder.getPlanLastDay());
        quitJobOrder.setWorkHandoverFocus(employee.getWorkHandoverFocus());
        quitJobOrder.setUpperDeptWorkHandoverFocus(employee.getWorkHandoverFocus());
        quitJobOrder.setUpperWorkHandoverFocus(employee.getWorkHandoverFocus());
        quitJobOrder.setInterWorkHandoverFocus(employee.getWorkHandoverFocus());
        quitJobOrder.setReasonSet(quitJobOrder.getReasonSet());
        quitJobOrder.setReasons(quitJobOrder.getReasons());
        quitJobOrder.setHrWorkHandoverFocus(employee.getWorkHandoverFocus());//工作交接重点
        return quitJobOrder;
    }

    /***
     * 功能：创建
     * @param request
     * @return
     */
    public QuitJobOrder createStore(SimpleRequest request) {

        QuitJobOrder quitJobOrder = request.getO(QuitJobOrder.class);
        Employee employee = employeeRepository.findByParty(((PartyRole)request.getPerson()).getParty());
        quitJobOrder = setQuitJobOrder(quitJobOrder,employee);
        if(exist(employee)) {
            throw new RuntimeException("当前员工已有未完成的离职单，不允许重复创建！");
        }

        Enumeration enumeration = enumerationRepository.findOne("000415");
        quitJobOrder.setQuitClass(enumeration);
        quitJobOrder.setState("create"); //设置当前的状态
        Date entryDate = employee.getEntryDate();
        Date planLastDay = quitJobOrder.getPlanLastDay();
        Date realLastDay = quitJobOrder.getRealLastDay();
        // 申请最后工作日填写小于入职日期时，系统不能保存（并提示原因）
        if (entryDate.after(realLastDay)) throw new RuntimeException("实际最后工作日小于入职日期");
        if (entryDate.after(planLastDay))throw new RuntimeException("申请最后工作日小于入职日期");
        //将人员档案的信息保存到离职申请单中（方便统计查询）

        //保存后自动转OA
        quitJobOrder = quitJobOrderRepository.saveAndFlush(quitJobOrder);
        invoke("hr.transfer.quitJobOrder.oa", quitJobOrder);

        return quitJobOrder;
    }


    /**
     * 判断当前员工是否有未完成的离职单
     * @param employee
     * @return
     */
    private boolean exist(Employee employee ){
        if(quitJobOrderRepository.findByEmployeeAndState(employee).isEmpty()){
            return false;
        }else {
            return true;
        }
    }

    /**
     * 判断当前员工是否有未完成的离职单
     * @param employee
     * @return
     */
    private boolean exist2(Employee employee ){
        if(quitJobOrderRepository.findByEmployeeAndState2(employee).isEmpty()){
            return false;
        }else {
            return true;
        }
    }

    /***
     * 功能： 修改
     * @param request
     * @return
     */
    public QuitJobOrder update(SimpleRequest request) {
        checkData(request);
        QuitJobOrder quitJobOrderDate = request.getO(QuitJobOrder.class);
        checkEntryDate(request,quitJobOrderDate.getQuitClass());
        Date planlastDay = quitJobOrderDate.getPlanLastDay();
        quitJobOrderDate.setApproveLastDay(planlastDay);
        quitJobOrderDate.setQuitJobDeptOpinionDate(planlastDay);
        quitJobOrderDate.setHrOpinionDay(planlastDay);
//        quitJobOrderDate = quitJobOrderRepository.findOne(quitJobOrderDate.getId());
        return quitJobOrderRepository.saveAndFlush(quitJobOrderDate);
    }

    /**
     * 检查 申请/实际 最后工作日 与 入职日期 的对比
     * @param request
     */
    public void checkEntryDate(SimpleRequest request,Enumeration enumeration){
        QuitJobOrder quitJobOrder = request.getO(QuitJobOrder.class);
        Date entryDate = quitJobOrder.getEmployee().getEntryDate();
        Date planLastDay = quitJobOrder.getPlanLastDay();
        Date realLastDay = quitJobOrder.getRealLastDay();

        // 申请最后工作日填写小于入职日期时，系统不能保存（并提示原因）
        if (entryDate.after(realLastDay)) throw new RuntimeException("实际最后工作日小于入职日期");
        if(enumeration == enumerationRepository.findByTypeAndValue("正常离职","quitClass")) {
            if (entryDate.after(planLastDay))throw new RuntimeException("申请最后工作日小于入职日期");
        }
    }

    /**
     * 检查数据
     * @param request
     */
    public void checkData(SimpleRequest request){
        String id = request.get("id");
        long versions = (int) request.get("version"); // 获取当前请求的版本信息
        QuitJobOrder quitJobOrder = quitJobOrderRepository.findOne(id);
        if (quitJobOrder == null) throw new RuntimeException("离职申请单【" + id + "】在系统中不存在。");
        if(quitJobOrder.getVersion() != versions) throw new RuntimeException("记录已更新或已删除，请重新提交！");  // 用于判断当前版本是否被修改
    }


    /***
     * 功能： 删除
     * @param request
     * @return
     * @throws Exception
     */
    public String delete(SimpleRequest request) throws Exception {
        checkData(request);// 用于判断当前版本是否被修改
        String id = request.get("id");
        quitJobOrderRepository.delete(id);

        return "删除成功！";
    }


    /***
     * 功能： 审核 (一期使用 二期使用OA审批流)
     *      * @param request
     *      * @return
     */
    public QuitJobOrder approve(SimpleRequest request) {
        checkData(request);
        QuitJobOrder quitJobOrder = request.getO(QuitJobOrder.class);
        Date date = dateAdd(quitJobOrder.getRealLastDay());
        //判断实际最后工作日+1天  是否 在当前时间 之前 如在当前之后 用定时任务触发
        quitJobHandle(quitJobOrder,quitJobOrder.getQuitClass(),date);

        return quitJobOrderRepository.saveAndFlush(quitJobOrder);
    }

    /**
     * 确认离职日期
     * @param request
     * @return
     */
    public QuitJobOrder confirm(SimpleRequest request){
        checkData(request);

        QuitJobOrder quitJobOrder = request.getO(QuitJobOrder.class);
        Date realLastDay = quitJobOrder.getRealLastDay();
        Date date = dateAdd(realLastDay);
        //判断实际最后工作日+1天  是否 在当前时间 之前 如在当前之后 用定时任务触发
        if(date.after(new Date())){
            quitJobOrder = quitJobOrderRepository.saveAndFlush(quitJobOrder);
        } else {
            Employee employee = quitJobOrder.getEmployee();
            //人员编制
            Staffing staffing = staffingRepository.findByCompanyAndBranchAndWorkPost(employee.getCompany(),employee.getWorkBranch(),employee.getPost());

            quitJob(quitJobOrder,quitJobOrder.getQuitClass());
            quitJobOrder = quitJobOrderRepository.findOne(quitJobOrder.getId());
        }
//        quitJobOrder.setState("confirm");
        quitJobOrder.setRealLastDay(realLastDay);
        return quitJobOrderRepository.saveAndFlush(quitJobOrder);
    }


    /**
     *  设置 人员档案 和 编制
     * @param quitJobOrder
     */
//    private void setStaffAndEmployee(QuitJobOrder quitJobOrder) {
//        Employee employee = quitJobOrder.getEmployee();
//        //人员编制
//       Staffing staffing = staffingRepository.findByCompanyAndBranchAndWorkPost(employee.getCompany(),employee.getWorkBranch(),employee.getPost());
//       if (staffing != null ) {
//            if ( staffing.getRealQty() < 0 || staffing.getRealQty() == 0 && staffing.getLeaveQty()<0 || staffing.getLeaveQty() == 0) {
//                throw new RuntimeException("当前部门职位的在职(待离职)人数已为0.请检查!");
//            } else {
//                staffing.setRealQty(staffing.getRealQty() - 1);//正式员工编制减1
//                staffing.setLeaveQty(staffing.getLeaveQty()-1);//将离职员工编制减1
//                quitJobOrder.setState("confirm"); //设置当前的状态
//                quitJobOrder.getEmployee().setEmployeeState(enumerationRepository.findOne("000089"));//人员档案员工状态修改成已离职
//                quitJobOrder.getEmployee().setQuitState(enumerationRepository.findOne("000413"));//人员档案离职状态修改成正常离职
//            }
//        } else {
//            throw new RuntimeException("当前没有该编制，请检查！");
//        }
////        quitJobOrder.setState("confirm");//直接确认离职
//        deleteUser(userRepository.findByParty(employee.getPartyId()));
//
//    }

    /**
     * 定时执行
     */
    public void updateLISQ(SimpleRequest request) throws RuntimeException{
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date time;
        ParsePosition pos = new ParsePosition(0);
        time= sdf.parse(sdf.format(new Date()),pos);
        List< QuitJobOrder> quitJobOrderList = quitJobOrderRepository.findAllByStateEqualsAndRealLastDayLessThan("approve",time);
        List< QuitJobOrder> quitJobOrderList2 = quitJobOrderRepository.findAllByStateEqualsAndRealLastDayLessThan("finish",time);
        quitJobOrderList.addAll(quitJobOrderList2);
        for (QuitJobOrder quitJobOrderDate: quitJobOrderList) {
            quitJobHandle(quitJobOrderDate,quitJobOrderDate.getQuitClass(),time);
            quitJobOrderRepository.saveAndFlush(quitJobOrderDate);
        }


    }

    /**
     * 取消离职
     * @param request
     */
    public QuitJobOrder cancel(SimpleRequest request){
        QuitJobOrder oldQuitJobOrder = request.getO(QuitJobOrder.class);
        QuitJobOrder quitJobOrder = quitJobOrderRepository.findOne(oldQuitJobOrder.getId());
        List<Staffing> staffings = staffingRepository.findByBranchAndWorkPost(quitJobOrder.getWorkBranch(),quitJobOrder.getPost());
        if (staffings != null ) {

            for (Staffing staffing: staffings ) {
                //找招聘单
                List<RecruitOrder> recruitOrders = recruitOrderRepository.findByStaffingAndState(staffing,"approve");
                recruitOrders.forEach(recruitOrder -> {
                   Set<Employee> employees = recruitOrder.getEmployeeSets();
                    employees.forEach(employee -> {
                        if(employee==quitJobOrder.getEmployee()){
                           employees.remove(employee);
                           recruitOrder.setCurrentRecruitQty(recruitOrder.getCurrentRecruitQty()-1);
                        }
                    });
                });
                Employee employee = quitJobOrder.getEmployee();
                employee = employeeRepository.findOne(employee.getId());
                if (employee.getEmployeeState().getId().equals("000089")){
//                     applyJobOrderService.createDingDingUser(employee,applyJobOrderService.findByEmployee(employee));
                    staffing.setRealQty(staffing.getRealQty()+1);
                    updateUser(userRepository.findByParty(employee.getParty()));
                    List<TransferRecord> transferRecordList;
                    try {
                        transferRecordList = transferRecordRepository.findByEmployee(quitJobOrder.getEmployee())
                                .stream().filter(transferRecord -> transferRecord.getTransferOut() != null)
                                .sorted(Comparator.comparing(TransferRecord::getTransferOn)).collect(Collectors.toList());
                    }catch (Exception e){
                        throw new RuntimeException("请检查调动记录单数据！");
                    }
                    if (!transferRecordList.isEmpty()){
                        TransferRecord transferRecord =transferRecordList.get(transferRecordList.size()-1);
                        transferRecordRepository.updateTransferOutToNull(transferRecord.getId());
                    }
                    try {
                        List<EmployContract> employContracts = employContractRepository.findByEmployeeAndStateOrderByCreateDate(quitJobOrder.getEmployee().getId());
                        if (!employContracts.isEmpty()){
                            EmployContract employContract = employContracts.get(0);
                            employContract.setState("done");
                            employContractRepository.save(employContracts);
                        }
                    }catch (Exception e){
                        throw new RuntimeException("请检查聘用合同数据！");
                    }
                }else{
                    if (quitJobOrder.getState().equals("approve")){
                        staffing.setLeaveQty(staffing.getLeaveQty()-1);//将离职员工编制减1
                    }

                }
                employee.setEmployeeState(enumerationRepository.findOne("000088"));//人员档案员工状态修改成在职
                employee.setQuitState(null);//人员档案离职状态修改成null
                employee.setLastUpdatedStamp(new Date());
                employeeRepository.saveAndFlush(employee);

            }
        } else {
            throw new RuntimeException("当前没有该编制，请检查！");
        }
        //修改离职申请单据状态(取消)
        quitJobOrder.setState("agree");
        setCarbonCopy(request);
        quitJobOrderRepository.saveAndFlush(quitJobOrder);
        quitJobOrder.setWrite(true);
        return quitJobOrder;

    }

    public QuitJobOrder updateOA(SimpleRequest request){
        QuitJobOrder quitJobOrder = request.getO(QuitJobOrder.class);
        quitJobOrder = quitJobOrderRepository.findOne(quitJobOrder.getId());
        quitJobOrder.setWrite(false);
        return quitJobOrder;
    }
    /**
     * 功能：查询离职申请单
     * @param request
     * @return
     * @throws Exception
     */
    public Page<QuitJobOrder> find(SimpleRequest request) throws Exception {
        List<Map> filters = request.get("condition");
        return quitJobOrderRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size")));
    }

    public QuitJobOrder findOne(SimpleRequest request){
        List<Map> filters = new ArrayList<>();
        JSONObject djid = new JSONObject();
        djid.put("field","id");
        djid.put("operator","EQ");
        djid.put("value",request.get("id"));
        List<String> branchIds = getCurrentAuth(request);
        if (branchIds.size() != 0){
            JSONObject auth = new JSONObject();
            auth.put("field","workBranch.id");
            auth.put("operator","IN");
            auth.put("value",branchIds);
            filters.add(auth);
        }
        filters.add(djid);
        QuitJobOrder quitJobOrder = quitJobOrderRepository.findOne(JpaDsl.toCriteria(filters)).orElse(null);
        return quitJobOrder;
    }

    public Page<QuitJobOrder> storeFindOne(SimpleRequest request){
        Employee employee = employeeRepository.findByParty(((PartyRole)request.getPerson()).getParty());
        List<Map> filters = request.get("condition");
        JSONObject djzt = new JSONObject();
        djzt.put("field","employee");
        djzt.put("operator","EQ");
        djzt.put("value",employee);
        filters.add(djzt);
        return quitJobOrderRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size")));
    }

    /**
     * 根据部门跟岗位进行判断 当前登录的角色 是否是主角色
     * @param barnch
     * @param post
     */
    public void judgePost(Branch barnch,WorkPost workPostpost,Post post){
        List<Post> posts = postRepository.findAllByBranchAndWorkPost(barnch,workPostpost);
        if (!posts.isEmpty()){
          if (!posts.contains(post))throw new RuntimeException("请使用" + posts.get(0).getName() + "角色转OA");
        }
    }




    /***
     * 功能 转OA start 节点
     * @param request
     * @return
     * @throws RuntimeException
     */
    public JSONObject transOA(SimpleRequest request) throws RuntimeException{
        //设置单据状态为处理中
        QuitJobOrder quitJobOrder = request.getO(QuitJobOrder.class);
        Post post = postRepository.findOne(request.getPostId());
        JSONObject tempJson = new JSONObject(MapUtil.mapped(quitJobOrder));
        quitJobOrder.setState("disposing");  //设置当前的状态为处理中
        WorkPost workPost = quitJobOrder.getPost();
        Branch branch = quitJobOrder.getWorkBranch();
        String companyId;
        if (quitJobOrder.getEmployee().getCompany()!=null){
            PartyRole company = quitJobOrder.getEmployee().getCompany();
            companyId = company.getParty().getCorporate().getOperation().getDescription();
//            companyId = quitJobOrder.getEmployee().getCompany().getId();

        }else {
            PartyRole company = post.getCompany();
            companyId = company.getParty().getCorporate().getOperation().getDescription();
//            companyId = post.getCompany().getId();//转OA人员角色的所属公司
        }
//        String companyId = post.getCompany().getId();//转OA人员角色的所属公司
        String workPostGroup =  workPost.getPostGroup().getName();

        if (quitJobOrder.getQuitClass().getDescription().equals("正常离职"))judgePost(branch,workPost,post);
        try{
            PartyRole party = quitJobOrder.getEmployee().getTestExaminer();
            List<User> userList = new ArrayList<>();
            if(party!=null){
                Employee employee = employeeRepository.findByParty(party.getParty());
                if (employee!=null && employee.getEmployeeState().getId().equals("000088")){
                    userList = userRepository.findByPartyRole(party);
                }else{//随机分配面试官
                    int x=(int)(Math.random()*2);
                    if (x==0){
                        userList = userRepository.findByPost("A0631");
                    }else {
                        userList = userRepository.findByPost("A0632");
                    }
                }
            } else {
                if (workPostGroup.equals("机电组")||workPostGroup.equals("钣喷组")){
                    userList = userRepository.findByPost("A0632");
                } else if(workPostGroup.equals("美容组")||workPostGroup.equals("服务顾问组")|| workPostGroup.equals("助理组")){
                    userList = userRepository.findByPost("A0631");
                }else{//随机分配面试官
                    int x=(int)(Math.random()*2);
                    if (x==0){
                        userList = userRepository.findByPost("A0631");
                    }else {
                        userList = userRepository.findByPost("A0632");
                    }
                }
            }
//            StringBuffer sb = new StringBuffer();
//            for (User user : userList) {
//                if (sb.length() > 0) {
//                    sb.append(";");
//                }
//                sb.append(user.getId());//格式 "xx;xx"
//            }
            int x =(int)(Math.random()*userList.size());
            quitJobOrder.setInterviewerId(userList.get(x).getId().toString());
        }catch (Exception e) {
            throw new RuntimeException("面试官为空");
        }
        if (workPost.getPostGroup().getId().equals("0011")){
            tempJson.put("workPostGroup","0008");
        }
        if (workPost.getPostGroup().getId().equals("0012")){
            tempJson.put("workPostGroup","0009");
        }
        tempJson.put("company",companyId);
        tempJson.put("workPostGroup",workPost.getPostGroup().getId()); //根据申请人的岗位分组
        tempJson.put("quitClass",quitJobOrder.getQuitClass().getDescription());//根据离职类型
        tempJson.put("state",quitJobOrder.getState());
        tempJson.put("version",quitJobOrder.getVersion());
        quitJobOrderRepository.saveAndFlush(quitJobOrder);
        return  tempJson;
    }

    public QuitJobOrder createCancel(SimpleRequest request){
        QuitJobOrder quitJobOrder = request.getO(QuitJobOrder.class);
        quitJobOrder.setState("cancelOA");
        invoke("hr.transfer.quitJobOrder.cancelOA", quitJobOrder);
        quitJobOrder.setWrite(true);
        return quitJobOrder;
    }

    /***
     * 功能 取消离职转OA start 节点
     * @param request
     * @return
     * @throws RuntimeException
     */
    public JSONObject cancelOA(SimpleRequest request) throws RuntimeException{
        //设置单据状态为处理中
        QuitJobOrder quitJobOrder = request.getO(QuitJobOrder.class);
        Post post = postRepository.findOne(request.getPostId());
        JSONObject tempJson = new JSONObject(Objects.requireNonNull(MapUtil.mapped(quitJobOrder)));
        if(quitJobOrder.getRepeal() == null )  throw new RuntimeException("取消离职原因不能为空!");
        if(exist2(quitJobOrder.getEmployee())) {
            throw new RuntimeException("当前员工有 未完成/在审批中 的离职单");
        }
        WorkPost workPost = quitJobOrder.getPost();
        String companyId;
        if (quitJobOrder.getEmployee().getCompany()!=null){
            PartyRole company = quitJobOrder.getEmployee().getCompany();
            companyId = company.getParty().getCorporate().getOperation().getDescription();
//            companyId = quitJobOrder.getEmployee().getCompany().getId();
        }else {
            PartyRole company = post.getCompany();
            companyId =company.getParty().getCorporate().getOperation().getDescription();
//            companyId = post.getCompany().getId();//转OA人员角色的所属公司
        }
        String workPostGroup =  workPost.getPostGroup().getName();
        try{
            PartyRole party = quitJobOrder.getEmployee().getTestExaminer();
            List<User> userList = new ArrayList<>();
            if(party!=null){
                Employee employee = employeeRepository.findByParty(party.getParty());
                if (employee!=null && employee.getEmployeeState().getId().equals("000088")){
                    userList = userRepository.findByPartyRole(party);
                }else{//随机分配面试官
                    int x=(int)(Math.random()*2);
                    if (x==0){
                        userList = userRepository.findByPost("A0631");
                    }else {
                        userList = userRepository.findByPost("A0632");
                    }
                }
            } else {
                if (workPostGroup.equals("机电组")||workPostGroup.equals("钣喷组")){
                    userList = userRepository.findByPost("A0632");
                } else if(workPostGroup.equals("美容组")||workPostGroup.equals("服务顾问组")|| workPostGroup.equals("助理组")){
                    userList = userRepository.findByPost("A0631");
                }else{//随机分配面试官
                    int x=(int)(Math.random()*2);
                    if (x==0){
                        userList = userRepository.findByPost("A0631");
                    }else {
                        userList = userRepository.findByPost("A0632");
                    }
                }
            }

            int x =(int)(Math.random()*userList.size());
            quitJobOrder.setInterviewerId(userList.get(x).getId().toString());
//            for (User user : userList) {
//                if (sb.length() > 0) {
//                    sb.append(";");
//                }
//                sb.append(user.getId());//格式 "xx;xx"
//            }
//            quitJobOrder.setInterviewerId(sb.toString());
        }catch (Exception e) {
            throw new RuntimeException("面试官为空");
        }
        if (workPost.getPostGroup().getId().equals("0011")){
            tempJson.put("workPostGroup","0008");
        }
        if (workPost.getPostGroup().getId().equals("0012")){
            tempJson.put("workPostGroup","0009");
        }
        tempJson.put("company",companyId);
        tempJson.put("workPostGroup",workPost.getPostGroup().getId()); //根据申请人的岗位分组
        tempJson.put("state",quitJobOrder.getState());
        tempJson.put("version",quitJobOrder.getVersion());
        quitJobOrderRepository.saveAndFlush(quitJobOrder);
        return  tempJson;
    }
    /**
     *  删除角色权限
     * @param userList
     */
    private void deleteUser(List<User> userList){
        JSONArray synPersonList = new JSONArray();  // 同步旧框架 使用
        for (User user : userList ) {
            JSONObject synPerson = new JSONObject();
            //不能使用删除 使用禁用标记
            user.setDisable(true);
            userRepository.saveAndFlush(user);
            apesLoggerService.sendSynEvent("event:ir.logger.create", MapUtil.mapper("businessType", "User",
                    "businessKey", user.getId(), "operate", "禁用角色", "workPostName",null, "operator_id", 1));
            this.synSaveUser(user);
        }
    }

    /**
     *  恢复角色权限
     * @param userList
     */
    private void updateUser(List<User> userList){
        for (User user : userList ) {
            JSONObject synPerson = new JSONObject();
            //不能使用删除 使用禁用标记
            user.setDisable(false);
            userRepository.saveAndFlush(user);
            apesLoggerService.sendSynEvent("event:ir.logger.create", MapUtil.mapper("businessType", "User",
                    "businessKey", user.getId(), "operate", "启用角色", "workPostName",null, "operator_id", 1));
            this.synSaveUser(user);
        }
    }

    /**
     * 同步user数据到 旧框架
     * @param user
     * @return
     */
    public boolean synSaveUser(User user){
        //同步数据到 旧框架
        JSONObject setUser = new JSONObject();
        StringBuffer sRoleList = new StringBuffer();  // 同步旧框架 使用
        setUser.put("RYID",user.getOrigin());
        setUser.put("RYMC",user.getName());
        setUser.put("CZYMM",user.getPassword());
        setUser.put("CZYLX",0);//操作员类型（0:内部员工；1：会员客户；2：供应商；3：线上；4：it服务商）
        if (user.isDisable()){
            setUser.put("CZYZT",1);//操作员状态（0：正常；1：注销；2：冻结）
        } else {
            setUser.put("CZYZT",0);//操作员状态（0：正常；1：注销；2：冻结）
        }
        List<Post> postLists = user.getPosts();
        if (postLists.size()>0) {
            postLists.forEach(yRole -> {
                sRoleList.append(yRole.getOrigin() + ";");

            });
        }
        setUser.put("Roles",sRoleList);
        String topic = "event:hr.hrTransferSyn.synUser";
        return (Boolean) EventUtil.sendSynEvent(this, topic, setUser).stream().findFirst().get();
    }


    /**
     * 执行离职操作
     * @param quitJobOrder
     */
    private QuitJobOrder quitJob(QuitJobOrder quitJobOrder,Enumeration quitState){
        saveQuitJobLog(quitJobOrder.getId());
        //离职单为确认离职状态一级主管确认后不再进行离职
        if(quitJobOrderRepository.findOne(quitJobOrder.getId()).getState().equals("confirm")) return quitJobOrderRepository.saveAndFlush(quitJobOrder);
        List<Staffing> staffings = staffingRepository.findByBranchAndWorkPost(quitJobOrder.getWorkBranch(),quitJobOrder.getPost());
        Job job1 = jobRepository.findOne("0013");//临时工
        Job job2 = jobRepository.findOne("0014");//小时工
        Date date =dateAdd(quitJobOrder.getRealLastDay());
        if (quitState ==  enumerationRepository.findOne("000416")){
            if (staffings != null ) {
                for (Staffing staffing: staffings ) {
                    if(quitJobOrder.getJob()!=job1 && quitJobOrder.getJob()!= job2 && !("000394").equals(quitJobOrder.getOnDutyState().getId()) && !("000118").equals(quitJobOrder.getOnDutyState().getId())) {
                        if (staffing.calcQty() < 0 || staffing.calcQty() == 0 ) {
                            throw new RuntimeException("当前部门 "+quitJobOrder.getWorkBranch().getId() +" "+quitJobOrder.getWorkBranch().getName()+" 职位 "+quitJobOrder.getPost().getId()+" "+quitJobOrder.getPost().getName()+" 的在职人数已为0.请检查!");
                        } else {
                            if ("03".equals(quitJobOrder.getEmployee().getOnDutyState().getId())) {
                                staffing.setRealQty(staffing.getRealQty() - 1);
                            } else {
                                staffing.setProbationQty(staffing.getProbationQty() - 1);
                            }
                        }
                    }
                }
            }else {
                throw new RuntimeException("当前没有该编制，请检查！");
            }
        }else{
            if (staffings != null ) {
                for (Staffing staffing: staffings ) {
                    if (quitJobOrder.getJob()!=job1 && quitJobOrder.getJob()!= job2 && !("000394").equals(quitJobOrder.getOnDutyState().getId()) && !("000118").equals(quitJobOrder.getOnDutyState().getId())){
                        if(!date.after(new Date())& (!quitJobOrder.getState().equals("approve"))&(!quitJobOrder.getState().equals("finish"))){
                            if (staffing.calcQty() < 0 || staffing.calcQty() == 0 ) {
                                throw new RuntimeException("当前部门 "+quitJobOrder.getWorkBranch().getId() +" "+quitJobOrder.getWorkBranch().getName()+" 职位 "+quitJobOrder.getPost().getId()+" "+quitJobOrder.getPost().getName()+" 的在职人数已为0.请检查!");
                            } else {
                                if ("03".equals(quitJobOrder.getEmployee().getOnDutyState().getId())) {
                                    staffing.setRealQty(staffing.getRealQty() - 1);
                                } else {
                                    staffing.setProbationQty(staffing.getProbationQty() - 1);
                                }
                            }
                        } else {
                            if (staffing.getRealQty() < 0 || staffing.getRealQty() == 0 && staffing.getLeaveQty()<0 || staffing.getLeaveQty() == 0) {
                                throw new RuntimeException("当前部门 "+quitJobOrder.getWorkBranch().getId() +" "+quitJobOrder.getWorkBranch().getName()+" 职位 "+quitJobOrder.getPost().getId()+" "+quitJobOrder.getPost().getName()+" 的在职人数或者待离职人数已为0.请检查!");
                            }else {
                                staffing.setRealQty(staffing.getRealQty() - 1);
                                staffing.setLeaveQty(staffing.getLeaveQty() - 1);
                            }
                        }

                    } else {
                        staffing.setLeaveQty(staffing.getLeaveQty() - 1);
                    }
                }
            }else {
                throw new RuntimeException("当前没有该编制，请检查！");
            }
        }

        quitJobOrder.setState("confirm"); //设置当前的状态
        quitJobOrder.getEmployee().setEmployeeState(enumerationRepository.findOne("000089"));//人员档案员工状态修改成已离职
        quitJobOrder.getEmployee().setQuitState(quitState);//设置人员档案离职状态
        quitJobOrder.getEmployee().setLastUpdatedStamp(new Date());
        deleteUser(userRepository.findByParty(quitJobOrder.getEmployee().getParty()));
        //将 状态同步到 TMS系统 司机管理
        invoke("tms.chauffeur.updateState",  quitJobOrder.getEmployee());

        List<ApplyJobOrder> list=applyJobOrderRepository.findByEmployee(quitJobOrder.getEmployee());
        list.forEach(applyJobOrder->{
            String state=applyJobOrder.getState();
            if(!("delete".equals(state)||"depart".equals(state)||"cancel".equals(state))){
                applyJobOrder.setState("depart");  //设置入职单为离职状态
                applyJobOrderRepository.saveAndFlush(applyJobOrder);
            }
        });

        List<TransferRecord> transferRecordList ;
        //更新最新的调动记录单的调离时间
        try {
            transferRecordList = transferRecordRepository.findByEmployee(quitJobOrder.getEmployee())
                    .stream().filter(transferRecord -> transferRecord.getTransferOut() == null)
                    .sorted(Comparator.comparing(TransferRecord::getTransferOn)).collect(Collectors.toList());
        }catch (Exception e){
            throw new RuntimeException("请检查调动记录单数据！");
        }
        try {
            List<EmployContract> employContracts = employContractRepository.findByEmployeeAndStateOrderByCreateDate(quitJobOrder.getEmployee().getId());
            if (!employContracts.isEmpty()){
                EmployContract employContract = employContracts.get(0);
                employContract.setState("repeal");
                employContractRepository.save(employContracts);
                apesLoggerService.sendSynEvent("event:ir.logger.create", MapUtil.mapper("businessType", "EmployContract",
                        "businessKey", employContract.getId(), "operate", "确认离职终止合同","workPostName",null, "operator_id", 1));
            }
        }catch (Exception e){
            throw new RuntimeException("请检查聘用合同数据！");
        }
        if (!transferRecordList.isEmpty()){
            TransferRecord transferRecord =transferRecordList.get(transferRecordList.size()-1);
            transferRecord.setTransferOut(quitJobOrder.getRealLastDay());
            transferRecordRepository.save(transferRecord);
        }
        // 岗位职能为总部职能的
        if("002026".equals(quitJobOrder.getPost().getPostGroup().getJobFunction().getId())){
            sendSynEvent("event:wf.carbonCopy", mapper(
                    "sourceBusinessType", "QuitJobOrder",
                    "sourceBusinessKey",quitJobOrder.getId(),
                    "operate", "同意离职",
                    "content", "总部员工离职,请及时处理",
                    "from_id",1,
                    "to_id", Arrays.asList(819).stream().map(userId -> {
                        JSONObject jo = new JSONObject();
                        jo.put("id", userId);
                        return jo;
                    }).collect(Collectors.toList()),
                    "processDefinitionName", "支援/调动单",
                    "formId", "form/hr.transfer.quitJobOrderStore",
                    "api", "hr.transfer.quitJobOrder.findOne",
                    "checked", false
            ));
        }
        return quitJobOrderRepository.saveAndFlush(quitJobOrder);
    }

    /**
     * 审批流使用
     * @param request
     */
    private QuitJobOrder quitJob2(SimpleRequest request){
        QuitJobOrder oldQuitJob = request.getO(QuitJobOrder.class);
        QuitJobOrder newQuitJob = quitJobOrderRepository.findOne(oldQuitJob.getId());
        newQuitJob.setFinish(true);
//        Date date = new Date();
//        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
        Date currentTime = new Date();
        if(newQuitJob.getQuitJobDeptOpinionDate() != null){
            newQuitJob.setQuitJobDeptOpinionDate(DateUtil.dateToDate(newQuitJob.getQuitJobDeptOpinionDate(),DateUtil.SHOW_DATE_FORMAT));
//            quitJobOrder.setRealLastDay(quitJobOrder.getQuitJobDeptOpinionDate());
            newQuitJob = quitJobOrderRepository.saveAndFlush(newQuitJob);
        }
        Date realLastDay = newQuitJob.getRealLastDay();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(currentTime);
        String LastDay = formatter.format(realLastDay);
        try {
            currentTime = formatter.parse(dateString);
            realLastDay = formatter.parse(LastDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }

//        if ( fmt.format().equals(fmt.format(date))){
//           date = dateAdd(quitJobOrder.getRealLastDay());
//       } else {
//           date = quitJobOrder.getRealLastDay();
//       }
        Enumeration employeeState =newQuitJob.getEmployee().getEmployeeState();
        Enumeration e = enumerationRepository.findByTypeAndValue("已离职","employeeState");
        if (employeeState != e){ // 如果还未离职
            // 假如 离职类型是正常离职且 实际最后工作日 大于或等于 当前日期 是 直接设为 审批通过 否则 直接离职
            if (newQuitJob.getQuitClass()== enumerationRepository.findByTypeAndValue("正常离职","quitClass")){
                if  (!realLastDay.before(currentTime)){
                    newQuitJob.setState("finish");//审批结束
                    quitJobOrderRepository.saveAndFlush(newQuitJob);
                } else{
                    quitJob(newQuitJob,newQuitJob.getQuitClass());
                }
            }

        }

//           List<Staffing> staffings = staffingRepository.findByBranchAndWorkPost(quitJobOrder.getWorkBranch(),quitJobOrder.getPost());
//           if (staffings != null ) {
//               for (Staffing staffing: staffings ) {
//                   staffing.setLeaveQty(staffing.getLeaveQty() - 1);//将离职员工编制+1
//               }
//           } else {
//               throw new RuntimeException("当前没有该编制，请检查！");
//           }
//        if(!quitJobOrder.getState().equals("confirm")) {
//           quitJobHandle(quitJobOrder, quitJobOrder.getQuitClass(), date);
//        }
//        if (quitJobOrder.getState().equals("approve")) {
//            quitJobOrder.setState("finish");//审批结束
//            quitJobOrderRepository.saveAndFlush(quitJobOrder);
//        }
        return quitJobOrderRepository.saveAndFlush(newQuitJob);
    }


    /**
     * 离职处理(未交接离职，正常离职（实际离职日期+1 是否在当前日期前）)
     * @param quitJobOrder
     * @param quitClass
     * @param date
     */
    private void quitJobHandle(QuitJobOrder quitJobOrder ,Enumeration quitClass,Date date ){
        List<Staffing> staffings = staffingRepository.findByBranchAndWorkPost(quitJobOrder.getWorkBranch(),quitJobOrder.getPost());
        Employee employee = quitJobOrder.getEmployee();
        if (!employee.getEmployeeState().getId().equals("000089")){
            if (quitClass  == enumerationRepository.findOne("000416")) {
                quitJob(quitJobOrder, enumerationRepository.findOne("000416") );
            } else {
                if(date.after(new Date())){
                    staffings.forEach(staffing -> {
                        staffing.setLeaveQty(staffing.getLeaveQty() + 1);//将离职员工编制+1
                    });

                    //预离职处理
                    quitJobOrder.setState("approve");
                    quitJobOrder.getEmployee().setQuitState(enumerationRepository.findOne("000412"));//人员档案离职状态修改成预离职
                    quitJobOrder.getEmployee().setLastUpdatedStamp(new Date());
                } else {
                    quitJob(quitJobOrder,enumerationRepository.findOne("000413"));
                }
            }

        }

    }

    /**
     * 传入的时间加一天
     * @param date
     * @return
     */
    private Date dateAdd(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, +1);//+1今天的时间加一天
        return calendar.getTime();
    }

    /**
     * 一级主管同意离职后 进行离职操作
     * @param
     */
    private QuitJobOrder beforehand(SimpleRequest request){
        QuitJobOrder quitJobOrder = request.getO(QuitJobOrder.class);
        quitJobOrder = quitJobOrderRepository.findOne(quitJobOrder.getId());
        //上级建议最后工作日格式化成年月日，带分秒导致后面判断离职错误
        quitJobOrder.setQuitJobDeptOpinionDate(DateUtil.dateToDate(quitJobOrder.getQuitJobDeptOpinionDate(),DateUtil.SHOW_DATE_FORMAT));
//        quitJobOrder.setRealLastDay(quitJobOrder.getQuitJobDeptOpinionDate());
        quitJobOrder = quitJobOrderRepository.saveAndFlush(quitJobOrder);
        Date date = dateAdd(quitJobOrder.getRealLastDay());
        this.quitJobHandle(quitJobOrder,quitJobOrder.getQuitClass(),date);
        return quitJobOrder;
    }



    /**
     * 设置抄送人
     * @param request
     * @return
     */
    public SimpleRequest setCarbonCopy(SimpleRequest request){
        //A0029
        JSONObject temJson = request.getJO();
        List<User> userList =userRepository.findByPost("A0029");
        List<JSONObject> maps = new ArrayList<>();
        if (userList!=null){
            userList.forEach(user -> {
                JSONObject object = new JSONObject();
                object.put("disable",user.isDisable());
                object.put("password",user.getPassword());
                object.put("id",user.getId());
                object.put("posts",user.getPosts());
                object.put("origin",user.getOrigin());
                object.put("person",user.getPerson());
                object.put("innerBusinessKey",user.getInnerBusinessKey());
                object.put("name",user.getName());
                object.put("version",user.getVersion());
                maps.add(object);
            });
        }
        if (!temJson.containsKey("wf_carbonCopy")){
            temJson.put("wf_carbonCopy",maps);
        } else {
            List<Object> list = maps.stream().map(jsonObject -> jsonObject.get("id")).collect(Collectors.toList());
            boolean con = false;
            JSONArray wf_carbonCopy = temJson.getJSONArray("wf_carbonCopy");
            for (int i = 0; i < wf_carbonCopy.size(); i++) {
                JSONObject object = wf_carbonCopy.getJSONObject(i);
                if (list.contains(object.get("id"))){
                    con = true;
                }
            }
            if (!con){
                wf_carbonCopy.addAll(maps);
            }
            temJson.put("wf_carbonCopy", wf_carbonCopy);
        }
        request.setData(temJson);
        return request;
    }
    /**
     * 获取直属上级
     * @param request
     */
    public QuitJobOrder getSuperior(SimpleRequest request){
        QuitJobOrder quitJobOrder = request.getO(QuitJobOrder.class);
        String  string = request.get("wf_comments");
        quitJobOrder.setDeptOpinion(string);
        quitJobOrder.setSuperior( ""+ ((User)getCurrentUser(request)).getId());
//        setCarbonCopy(request);
        return quitJobOrderRepository.saveAndFlush(quitJobOrder);
    }
    /**
     *  保存人资取消离职意见
     * @param request
     */
    public QuitJobOrder hrCancelOpinion(SimpleRequest request){
        QuitJobOrder quitJobOrder = request.getO(QuitJobOrder.class);
        String  string = request.get("wf_comments");
        String  string2 = request.get("opinion");
        String s = request.get("wf_variable_wf_state");
        if (s.equals("1")){
            quitJobOrder.setDeptCancelRefuse(true);
        }
        quitJobOrder.setHrCancelOpinion(string);
        quitJobOrder = quitJobOrderRepository.saveAndFlush(quitJobOrder);
        quitJobOrder.setWrite(false);
        return quitJobOrder;
    }



    /**
     *  各级取消离职审批意见为拒绝时离职处理
     * @param request
     */
    public void setQuitJob(SimpleRequest request){
        QuitJobOrder quitJobOrder = request.getO(QuitJobOrder.class);
        List<Staffing> staffings = staffingRepository.findByBranchAndWorkPost(quitJobOrder.getWorkBranch(),quitJobOrder.getPost());
        String state = request.get("wf_variable_wf_state");
        if (state.equals("0")) {
            staffings.forEach(staffing -> {
                staffing.setLeaveQty(staffing.getLeaveQty()+1);
            });
            quitJobHandle(quitJobOrder,quitJobOrder.getQuitClass(),dateAdd(quitJobOrder.getRealLastDay()));
            quitJobOrderRepository.saveAndFlush(quitJobOrder);
        }

    }
    /**
     *  各级取消离职审批意见为拒绝时抄送
     * @param request
     */
    public void carbonCopyTo(SimpleRequest request){
        String state = request.get("wf_variable_wf_state");
        if (state.equals("0")){
            setCarbonCopy(request);
        }
    }



    /**
     *  保存直属部门取消离职意见
     * @param request
     */
    public QuitJobOrder hqInterCancelOpinion(SimpleRequest request){
        QuitJobOrder quitJobOrder = request.getO(QuitJobOrder.class);
        String  string = request.get("wf_comments");
        String  string2 = request.get("opinion");
        String s = request.get("wf_variable_wf_state");
        if (s.equals("1")){
            quitJobOrder.setHqInterCancelRefuse(true);
        }
        quitJobOrder.setHqInterCancelOpinion(string);
        quitJobOrder = quitJobOrderRepository.saveAndFlush(quitJobOrder);
        quitJobOrder.setWrite(false);
        return quitJobOrder;
    }

    /**
     * 直属上级取消离职意见
     * @param request
     */
    public QuitJobOrder DeptCancelOpinion(SimpleRequest request){
        QuitJobOrder quitJobOrder = request.getO(QuitJobOrder.class);
        String  string = request.get("wf_comments");
        String s = request.get("wf_variable_wf_state");
        if (s.equals("1")){
            quitJobOrder = repeal(request);
            quitJobOrder.setDeptCancelRefuse(true);
            quitJobOrder.setState("agree");//同意取消离职
        }else{
            if("000089".equals(quitJobOrder.getEmployee().getEmployeeState().getId())) quitJobOrder.setState("confirm");
            quitJobHandle(quitJobOrder,quitJobOrder.getQuitClass(),dateAdd(quitJobOrder.getRealLastDay()));
//            quitJobOrder = quitJobOrderRepository.findOne(quitJobOrder.getId());
        }
        quitJobOrder.setDeptCancelOpinion(string);
        quitJobOrder.setSuperior( ""+((User)this.getCurrentUser(request)).getId());
        quitJobOrder = quitJobOrderRepository.saveAndFlush(quitJobOrder);
        quitJobOrder.setWrite(false);
        return quitJobOrder;
    }
    /**
     *  保存人资意见
     * @param request
     */
    public QuitJobOrder hrOpinion(SimpleRequest request){
        QuitJobOrder quitJobOrder = request.getO(QuitJobOrder.class);
        String  string = request.get("wf_comments");
        String  string2 = request.get("opinion");
        quitJobOrder.setHrOpinion(string);
        quitJobOrder = quitJobOrderRepository.saveAndFlush(quitJobOrder);
        quitJobOrder.setWrite(false);
        return quitJobOrder;
    }

    /**
     *  保存面试官意见
     * @param request
     */
    public QuitJobOrder interOpinion(SimpleRequest request){
        QuitJobOrder quitJobOrder = request.getO(QuitJobOrder.class);
        String  string = request.get("wf_comments");
        String  string2 = request.get("opinion");
        quitJobOrder.setInterOpinion(string);
        quitJobOrder = quitJobOrderRepository.saveAndFlush(quitJobOrder);
        quitJobOrder.setWrite(false);
        return quitJobOrder;
    }


    /**
     *  保存直属部门意见
     * @param request
     */
    public QuitJobOrder hqInterOpinion(SimpleRequest request){
        QuitJobOrder quitJobOrder = request.getO(QuitJobOrder.class);
        String  string = request.get("wf_comments");
        String  string2 = request.get("opinion");
        quitJobOrder.setHqInterOpinion(string);
        quitJobOrder = quitJobOrderRepository.saveAndFlush(quitJobOrder);
        quitJobOrder.setWrite(false);
        return quitJobOrder;
    }


    /**
     * 获取直属上级
     * @param request
     */
    public QuitJobOrder getUpper(SimpleRequest request){
        QuitJobOrder quitJobOrder = request.getO(QuitJobOrder.class);
        try{
            List<Post> postList = postRepository.findAllByBranchAndWorkPost(quitJobOrder.getWorkBranch(),quitJobOrder.getPost().getParents());
            //一般只有一个
            Set<User> users = postList.get(0).getAssignedUsers();
            users.forEach(user -> {
                quitJobOrder.setSuperior(user.getId()+";");
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return quitJobOrderRepository.saveAndFlush(quitJobOrder);
    }

    /**
     * 找到个人最新的离职单
     * @param request
     * @return
     */
    public List<Map> findByEmployee(SimpleRequest request){
        Employee employee = employeeRepository.getOne(request.get("employeeId"));
        List<QuitJobOrder> quitJobOrderList = quitJobOrderRepository.findByEmployee(employee).stream().
//                filter(quitJobOrder -> !(quitJobOrder.getState().equals("cancel") || quitJobOrder.getState().equals("repeal"))).
                sorted(Comparator.comparing(QuitJobOrder:: getCreateDate).reversed()).collect(Collectors.toList());
        List<Map> quitList =new ArrayList<>();
        if(!quitJobOrderList.isEmpty()){
            quitJobOrderList.forEach(quitJobOrder->{
                quitList.add(
                    MapUtil.mapper(
                            "id",quitJobOrder.getId(),
                            "createDate", DateUtil.format(quitJobOrder.getCreateDate(),DateUtil.SHOW_DATE_FORMAT)
                    )
                );
            });
        }
        return quitList;
    }
    public QuitJobOrder selectLastOne(List<QuitJobOrder> list) {
        QuitJobOrder card = list.get(0);

        Long dates[] = new Long[list.size()];
        for (int i = 1; i <= list.size(); i++) {
            // 把date类型的时间对象转换为long类型，时间越往后，long的值就越大，
            // 所以就依靠这个原理来判断距离现在最近的时间
            dates[i-1] = list.get(i-1).getCreateDate().getTime();
        }
        Long maxIndex = dates[0];// 定义最大值为该数组的第一个数
        for (int j = 0; j < dates.length; j++) {
            if (maxIndex < dates[j]) {
                maxIndex = dates[j];
                // 找到了这个j
                card = list.get(j);
            }
        }
        return card;
    }

    /**
     * 终止 （废除离职单）
     * @param request
     */
    public QuitJobOrder repeal(SimpleRequest request){
        QuitJobOrder quitJobOrder = request.getO(QuitJobOrder.class);
        Employee employee = quitJobOrder.getEmployee();
        employee = employeeRepository.findOne(employee.getId());
        //修改人员档案
        employee.setEmployeeState(enumerationRepository.findOne("000088"));//人员档案员工状态修改成在职
        employee.setQuitState(null);//设置人员档案离职状态
        employee.setLastUpdatedStamp(new Date());
        List<TransferRecord> transferRecords = transferRecordRepository.findByEmployee(employee);
        transferRecords.get(transferRecords.size() - 1).setTransferOut(null);
        quitJobOrder.setDeptCancelRefuse(true);
        quitJobOrder.setState("agree");//同意取消离职
        //修改人员编制
        if (quitJobOrder.getState().equals("confirm")){
            updateStaffing(employee.getCompany(),quitJobOrder.getWorkBranch(),quitJobOrder.getPost(),1,0);
//            applyJobOrderService.createDingDingUser(employee,applyJobOrderService.findByEmployee(employee));
        }else{
            updateStaffing(employee.getCompany(),quitJobOrder.getWorkBranch(),quitJobOrder.getPost(),0,-1);
        }

        //人员角色
        List<User> userList = userRepository.findByParty(quitJobOrder.getEmployee().getParty());
        updateUser(userList);
//        userList.forEach(user -> {
//            user.setDisable(false);
//            userRepository.saveAndFlush(user);
//        });
        quitJobOrder.setState("agree");
        return quitJobOrderRepository.saveAndFlush(quitJobOrder);
    }


    /**
     * 功能：更新 编制 信息
     * @param
     */
    private void updateStaffing(PartyRole company, Branch branch, WorkPost workPost, int iRealQtyAdd, int iLeaveQtyAdd)throws RuntimeException {
        // 更新 编制 如无 增（一般情况不会无）
        List<Staffing> listStaffing = staffingRepository.findByBranchAndWorkPost(branch, workPost);
        Staffing staffing = new Staffing();
        int realQty = 0;
        int leaveQty = 0;
        if (listStaffing.size() > 0) {
            staffing = listStaffing.get(0);
            realQty = staffing.getRealQty();
            leaveQty = staffing.getLeaveQty();
        } else {
            staffing.setCompany(company);
            staffing.setBranch(branch);
            staffing.setWorkPost(workPost);
        }
        realQty = realQty+ iRealQtyAdd;
        leaveQty = leaveQty + iLeaveQtyAdd;
        staffing.setRealQty(realQty);
        staffing.setLeaveQty(leaveQty);
        staffingRepository.saveAndFlush(staffing);
    }

    /**
     * 未交接离职一级主管审批后进行离职操作
     * @return
     */
    public QuitJobOrder setQuitJobState(SimpleRequest request){
        QuitJobOrder quitJobOrder = request.getO(QuitJobOrder.class);
//        saveQuitJobLog(request.getJO().toString());
        //保存直属上级意见跟直属上级
        String  string = request.get("wf_comments");
        String s = request.get("wf_variable_wf_state");
        if(quitJobOrder.getQuitJobDeptOpinionDate() != null){
            quitJobOrder.setQuitJobDeptOpinionDate(DateUtil.dateToDate(quitJobOrder.getQuitJobDeptOpinionDate(),DateUtil.SHOW_DATE_FORMAT));
//            quitJobOrder.setRealLastDay(quitJobOrder.getQuitJobDeptOpinionDate());
            quitJobOrder = quitJobOrderRepository.saveAndFlush(quitJobOrder);
            Date date = dateAdd(quitJobOrder.getRealLastDay());
            if (s.equals("1")){
                quitJobHandle(quitJobOrder,quitJobOrder.getQuitClass(),date);
            }
        } else {
            if (s.equals("1")){
                quitJobHandle(quitJobOrder,quitJobOrder.getQuitClass(),dateAdd(quitJobOrder.getRealLastDay()));
            }
        }
        quitJobOrder = quitJobOrderRepository.findOne(quitJobOrder.getId());
        quitJobOrder.setDeptOpinion(string);
        quitJobOrder.setSuperior( ""+((User)this.getCurrentUser(request)).getId());
        return quitJobOrderRepository.saveAndFlush(quitJobOrder);
    }

    private void saveQuitJobLog(String payload) {
        Document document = new Document();
        document.put("payload", payload);
        document.put("date", LocalDateTime.now());
        mongoTemplate.getCollection("quitJobConnection").insertOne(document);
    }

    /**
     * 判断是否店长在修改自身的离职单
     * @param request
     * @return
     */
    public String findByRealLastDay(SimpleRequest request){
        Employee employee = employeeRepository.findByParty(((PartyRole)request.getPerson()).getParty());
        String id = request.get("id");
        QuitJobOrder quitJobOrder = quitJobOrderRepository.findOne(id);
        String mss = new String();
//       request.getO(QuitJobOrder.class);
        if (employee==quitJobOrder.getEmployee()) {
            mss = "不能自己确认自己的实际工作日！";
        }
        return mss;
    }


    public Page<QuitJobOrder> findByQuitClass(SimpleRequest request){
        Enumeration quitClass = enumerationRepository.findOne("000416");
        List<Map> filters = request.get("condition");
        JSONObject djzt = new JSONObject();
        djzt.put("field","quitClass");
        djzt.put("operator","EQ");
        djzt.put("value",quitClass);
        List<String> branchIds = getCurrentAuth(request);
        if (branchIds.size() != 0){
            JSONObject auth = new JSONObject();
            auth.put("field","workBranch.id");
            auth.put("operator","IN");
            auth.put("value",branchIds);
            filters.add(auth);
        }
        filters.add(djzt);
        return quitJobOrderRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size")));

    }

    public Page<QuitJobOrder> findByQuitClassStore(SimpleRequest request){
        Enumeration quitClass = enumerationRepository.findOne("000415");
        List<Map> filters = request.get("condition");
        JSONObject djzt = new JSONObject();
        djzt.put("field","quitClass");
        djzt.put("operator","EQ");
        djzt.put("value",quitClass);
        List<String> branchIds = getCurrentAuth(request);
        if (branchIds.size() != 0){
            JSONObject auth = new JSONObject();
            auth.put("field","workBranch.id");
            auth.put("operator","IN");
            auth.put("value",branchIds);
            filters.add(auth);
        }
        filters.add(djzt);
        return quitJobOrderRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size")));

    }

    public com.apestech.framework.json.JSONObject achievementsStore(SimpleRequest request){
        com.apestech.framework.json.JSONObject json = new com.apestech.framework.json.JSONObject();
        try {
            String body = request.getData().toString();
            json = com.apestech.framework.json.JSON.toJSON(body);
            Post post = postRepository.findOne(request.getPostId());
            Branch branch = post.getBranch();
            json.put("BRANCH_NAME",branch.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 调整离职日期
     * @param request
     * @return
     */
    public QuitJobOrder adjust(SimpleRequest request){
        checkData(request);
        QuitJobOrder quitJobOrder = request.getO(QuitJobOrder.class);
        checkEntryDate(request,quitJobOrder.getQuitClass());
        Date realLastDay = quitJobOrder.getRealLastDay();
        Date date = dateAdd(realLastDay);
        Employee employee = quitJobOrder.getEmployee();
        Enumeration employeeState = employee.getEmployeeState();
        Enumeration enumeration = enumerationRepository.findByTypeAndValue("已离职","employeeState");
        // 如果人员已离职，修改后的时间大于当前时间 将人员修改成在职 并将人员编制 在职加一，预离职加一
        if (employeeState == enumeration && date.after(new Date())){
            employee.setEmployeeState(enumerationRepository.findByTypeAndValue("在职","employeeState"));
            employee.setQuitState(enumerationRepository.findByTypeAndValue("预离职","quitState"));
//            Staffing staffing = staffingRepository.findByCompanyAndBranchAndWorkPost(employee.getCompany(),employee.getWorkBranch(),employee.getPost());
//            staffing.setLeaveQty(staffing.getLeaveQty() + 1);//将离职员工编制+1
//            staffing.setRealQty(staffing.getRealQty() +1);
            quitJobOrder.setState("approve");
            updateStaffing(employee.getCompany(),quitJobOrder.getWorkBranch(),quitJobOrder.getPost(),1,1);
        }
        // 如果人员在职，修改后的时间小于当前时间 ，执行离职操作
        if (employeeState != enumeration && !date.after(new Date())){
            quitJob(quitJobOrder,quitJobOrder.getQuitClass());
            quitJobOrder = quitJobOrderRepository.findOne(quitJobOrder.getId());
        }
//        quitJobOrder.setRealLastDay(realLastDay);
        return quitJobOrderRepository.saveAndFlush(quitJobOrder);
    }

    /**
     * 根据当前登录的人获取本地角色的查询权限
     * @param request 本地角色关联的本地权限的查询权限的业务部门
     * @return 行政部门列表
     */
    public List<String> getCurrentAuth(SimpleRequest request){
        List<String> branchIds = new ArrayList<>();
        List<LocalPermitItem> localPermitItems = SpringManager.getBean(LocalPermitItemRepository.class).find(request.getPostId(), "pp_search", "pt_dept");
        if (!localPermitItems.isEmpty()){
            //获取行政部门列表
            List<String> ids = new ArrayList<>();
            localPermitItems.forEach(e -> ids.add(e.getOrgId()));
            branchIds = SpringManager.getBean(DeptRepository.class).findDeptByIds(ids);
        }
        return branchIds;
    }

}
